<template>
    <el-container class="inventory_form_container">
        <el-main>
            <el-card class="box-card">
                <div slot="header" class="clearfix" style="padding-left: 0;">
                    <el-form ref="stockInventoryForm" :rules="isEditFlag ? rules : {}"
                             :model="formData" label-width="100px" v-enterToNext>
                        <el-row :gutter="15">
                            <el-col :span="8">
                                <el-form-item label="盘点单号" prop="code">
                                    <el-input v-model="formData.code" clearable :disabled="!isEditFlag"/>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="盘点日期" prop="check_date">
                                    <el-date-picker v-model="formData.check_date"
                                                    type="date" value-format="yyyy-MM-dd"
                                                    :disabled="!isEditFlag" style="width: 100%;"/>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="仓库" prop="warehouse_sid">
                                    <remote-select v-model="formData.warehouse_sid" :options="selectProps"
                                                   style="width: 100%" :disabled="!isEditFlag"
                                                   @event="handleSelectEvent"/>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-form>
                </div>
                <div class="card_content">
                    <div class="btn_area">
                        <div class="btn_area_left" v-if="review || isImport">
                            <el-input v-model="searchTxt" placeholder="请输入搜索物料" @input="querySearchAsync"
                                      style="width: 200px;"/>
                        </div>
                        <div class="btn_area_right" v-if="isImport">
                            <el-button type="success" style="text-align: right;" @click="handleOpenImportDialog">导入
                            </el-button>
                        </div>
                    </div>
                    <vxeTableTemplate :data="dataList" :options.sync="tableOptions"
                                      @event="handleTableEvent"/>
                </div>
            </el-card>
        </el-main>
    </el-container>
</template>

<script>
import tableRender from "@common/components/common/tableRender";
import provide from "@common/mixins/provide";

export default {
    extends: provide,
    name: "InventoryForm",
    props: {
        row: {
            type: Object,
            default: null,
        },
        detail: {
            type: Boolean,
            default: false,
        },
        review: {
            type: Boolean,
            default: false,
        },
        isImport: {
            type: Boolean,
            default: false,
        },
    },
    data() {
        const _this = this;
        return {
            importPermission: {
                check_router: '/jxcStockInventory',
                permission: 'jxc:stockInventory:import',
            },
            rules: {
                code: [
                    {required: true, message: "请输入盘点单号", trigger: "blur"},
                    {max: 32, message: "最大 32 位字符，内容过长，请删减", trigger: "blur",},
                ],
                check_date: [
                    {required: true, message: "请选择盘点日期", trigger: "change"},
                ],
                warehouse_sid: [
                    {required: true, message: "请选择仓库", trigger: "change"},
                ],
            },
            formData: {},
            selectionList: [],
            dataList: [],
            tableOptions: {
                ref: "JxcStockInventoryFormTable",
                container: ".inventory_form_container",
                keyboardConfig: {
                    isEdit: true,
                },
                showSummary: true,
                multiSelect: false,
                summaryArray: ['old_qty', 'check_qty'],
                columns: [],
                baseColumns: [
                    {
                        label: "物料",
                        prop: "goods_name",
                        align: "center",
                    },
                    {
                        label: "规格",
                        prop: "spec_name",
                        align: "center",
                        minWidth: 200,
                    },
                    {
                        label: "原数量",
                        prop: "old_qty",
                        align: "center",
                        width: 80,
                    },
                    {
                        label: "盘点数量",
                        prop: "check_qty",
                        align: "center",
                        width: 100,
                        editRender: {
                            name: "CustomInput",
                            autoselect: true,
                            props: {
                                integer: true,
                            },
                            events: {
                                input: _this.rewriteChangeRow,
                                enter: _this.handleEnterEvent,
                            },
                        },
                    },
                    {
                        label: "备注",
                        prop: "note_info",
                        align: "center",
                        width: 200,
                        editRender: {
                            name: 'CustomInput',
                            events: {
                                input: _this.rewriteChangeRow,
                                enter: _this.handleEnterEvent,
                            },
                        },
                    },
                ],
                operates: {
                    fixed: "right",
                    list: [
                        {
                            id: 'del',
                            icon: 'fa fa-trash-o',
                            size: 'mini',
                            type: 'danger',
                            show: true,
                            tooltip: {
                                content: '删除',
                            },
                            filter: (row) => {
                                return _this.isEditFlag;
                            },
                            method: (index, row) => {
                                let dataList = _this.dataList.map(item => $.extend({}, item));
                                dataList = dataList.filter(item => item._index !== row._index);
                                _this.dataList = _this.resetIndex(dataList);
                            }
                        }
                    ],
                },
                pagination: false,
            },
            oldCode: '',
            searchTxt: '',
            deepDataList: [],
            selectProps: {
                remote: _this.$api.API_FindJxcStockWarehouses,
                placeholder: '请选择仓库',
                optionProps: {
                    label: 'name',
                    value: 'sid',
                },
            },
            disableImportBtn: true,
        };
    },
    computed: {
        isEditFlag() {
            if (this.detail) {
                return false;
            }
            if (this.review) {
                return false;
            }
            if (this.isImport) {
                return false;
            }
            return true;
        },
        isNoAudit() {
            if (this.$utils.isEmpty(this.formData.id)) {
                return true;
            }
            return this.formData.state === 0;
        },
        disabledClear() {
            let filter = this.dataList.filter(item => this.$utils.isNotEmpty(item.new_position_sid));
            return !this.$utils.isNotEmptyList(filter);
        },
    },
    watch: {
        row: {
            handler() {
                this.init();
            },
            deep: true,
            immediate: true,
        },
    },
    methods: {
        async init() {
            const _this = this;
            if (!_this.row) {
                return;
            }
            _this.initTableOptions();
            if (_this.$refs.stockInventoryForm) {
                _this.$refs.stockInventoryForm.clearValidate();
            }
            let sid = _this.$route.query.sid;
            if (_this.$utils.isNotEmpty(_this.row.sid)) {
                sid = _this.row.sid;
            }
            if (_this.$utils.isNotEmpty(sid)) {
                await _this.initData(_this.row.sid);
            } else {
                _this.formData = {
                    check_date: _this.$XEUtils.toDateString(new Date(), 'yyyy-MM-dd'),
                };
                _this.generateCode();
            }
        },
        initTableOptions() {
            const _this = this;
            let columns = _this.tableOptions.baseColumns.map(item => $.extend({}, item));
            let operates = $.extend({}, _this.tableOptions.operates);
            let multiSelect = false;
            if ((!_this.review && !_this.isImport) && (!_this.isEditFlag || _this.isNoAudit)) {
                columns = columns.map(item => {
                    let obj = $.extend({}, item);
                    if (_this.isNoAudit && item.prop === 'position_name') {
                        obj.label = '物料位置';
                    }
                    delete obj.editRender;
                    delete obj.render;
                    return obj;
                });
                if (!_this.isEditFlag) {
                    operates = {};
                }
                if (_this.isNoAudit) {
                    if (!this.detail) {
                        columns = columns.filter(item => item.prop !== 'new_position_name');
                        columns = columns.filter(item => item.prop !== 'check_qty');
                    }
                    columns = columns.filter(item => item.prop !== 'note_info');
                }
            }
            if (_this.review || _this.isImport) {
                operates = {};
                multiSelect = true;
            }
            _this.tableOptions = $.extend({}, _this.tableOptions, {
                columns, operates, multiSelect,
                getMaxHeight() {
                    let height = $(_this.getActiveTabsContainer()).height();
                    return height * 0.8 - 250;
                },
            });
        },
        initData(sid) {
            let _this = this;
            return _this.fetchData(_this.$api.API_GetJxcStockInventoryBySid, {
                sid
            }).then(result => {
                let resData = result.data || {};
                _this.formData = resData;
                let itemList = (resData.item_list || []).map(item => {
                    let obj = $.extend({}, item);
                    if (_this.$utils.isEmpty(item.check_qty)) {
                        obj.check_qty = item.old_qty;
                    }
                    if (_this.$utils.isEmpty(item.note_info)) {
                        obj.note_info = '';
                    }
                    if (_this.$utils.isEmpty(item.new_position_sid)) {
                        obj.new_position_name = item.position_name;
                    }
                    return obj;
                });
                _this.dataList = _this.resetIndex(itemList);
                _this.deepDataList = _this.resetIndex(itemList);
                _this.oldCode = resData.code;
            }).catch(() => {
            });
        },
        handleTableEvent(event) {
            if (event.type === 'selectionChange') {
                this.selectionList = event.value;
            }
        },
        generateCode() {
            let _this = this;
            if (_this.$utils.isNotEmpty(_this.oldCode) && _this.oldCode === _this.formData.code) {
                return;
            }
            return _this.storeDispatch('base/getAutoOrderCode', {
                rule_code: 'jxc_stock_inventory',
            }).then(data => {
                _this.formData = $.extend({}, _this.formData, {
                    code: data,
                });
                _this.oldCode = data;
                if (_this.$refs.stockInventoryForm) {
                    _this.$refs.stockInventoryForm.clearValidate('code');
                }
            });
        },
        rewriteChangeRow({row, column}) {
            const _this = this;
            column = Object.assign({}, column, column.params)
            // 手动限制控制数字位数
            if (column.editRender && column.editRender.double) {
                _this.$set(row, column.prop, _this.$XEUtils.DoubleInput(row[column.prop], column.editRender.double));
            }
            if (column.editRender && column.editRender.integer) {
                _this.$set(row, column.prop, _this.$XEUtils.IntInput(row[column.prop]));
            }
            _this.editRow(row, column);
        },
        handleSelectEvent(event) {
            const _this = this;
            if (event.type === 'change') {
                _this.formData = $.extend({}, _this.formData, {
                    warehouse_sid: event.value,
                })
                _this.initStockGoods();
            }
        },
        initStockGoods() {
            const _this = this;
            _this.dataList = [];
            _this.deepDataList = [];
            if (_this.$utils.isEmpty(_this.formData.warehouse_sid)) {
                return;
            }
            _this.fetchData(_this.$api.API_FindJxcStockGoodPositionByPage, {
                warehouse_sid: _this.formData.warehouse_sid,
                nopage: '1',
            }).then(res => {
                let list = (res.data || []).map(item => {
                    return {
                        goods_sid: item.goods_sid,
                        product_sid: item.product_sid,
                        old_position_sid: item.position_sid,
                        goods_name: item.goods_name,
                        spec_name: item.spec_name,
                        position_name: item.warehouse_position_name,
                        old_qty: item.stock_qty,
                        check_qty: item.stock_qty,
                    };
                });
                _this.dataList = _this.resetIndex(list);
                _this.deepDataList = _this.resetIndex(list);
            }).catch(() => {
            });
        },

        handleOpenImportDialog() {
            const _this = this;
            _this.$ImportExcel({
                title: '导入',
                configFile: _this.$api.IMPORT_CONFIG_FILE_INVENTORY,
                uploadedShowData: true,
                event(event) {
                    if (event.type === 'beforeUpload') {
                        let fileName = event.file && event.file.name;
                        if (!_this.$utils.isNotEmpty(fileName) || !_this.$utils.isNotEmpty(_this.formData.code)) {
                            event.callback(false);
                            return;
                        }
                        let bol = String(fileName).includes(_this.formData.code)
                        if (bol) {
                            event.callback(true);
                            return;
                        }
                        _this.$message.error('导入' + fileName + '与本单号不符合，请检查！');
                        event.callback(false);
                    }
                },
                // 点击导入按钮执行方法
                importMethod(list, dialog) {
                    _this.handleImportData(list, dialog);
                },
            });
        },
        handleImportData(list, dialog) {
            const _this = this;
            if (!_this.$utils.isNotEmptyList(list)) {
                _this.$message.error('导入数据为空');
                return;
            }
            _this.fetchData(_this.$api.API_BatchSaveJxcStockInventoryItem, {
                list,
            }).then(() => {
                _this.$message.success('导入成功');
                dialog.visible = false;
                _this.init();
            }).catch(() => {
            });
        },
        async confirm() {
            const _this = this;
            let valid = await _this.validateForm('stockInventoryForm');
            if (!valid) {
                return false;
            }
            if (!_this.$utils.isNotEmptyList(_this.deepDataList)) {
                _this.$message.error('盘点明细不能为空');
                return false;
            }
            let subData = $.extend({}, _this.formData);
            subData.item_list = _this.deepDataList.map(item => {
                let obj = $.extend({}, item);
                obj.sn = item._index + 1;
                return obj;
            });
            let url = _this.$api.API_SaveJxcStockInventory;
            if (_this.review) {
                url = _this.$api.API_SaveJxcStockInventory4Review;
            }
            return _this.fetchData(url, subData).then(() => {
                _this.$message.success('保存成功！');
                return true;
            }).catch(() => {
                return false;
            });
        },
        querySearchAsync(queryString) {
            const _this = this;
            let list = _this.deepDataList;
            _this.dataList = !queryString ? list : list.filter(t => t.goods_name.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
        },
        editRow(row, column) {
            const _this = this;
            if (!row || _this.deepDataList.length === 0) {
                return;
            }
            let filterList = _this.deepDataList.filter(t => t.product_sid === row.product_sid);
            if (column.prop) {
                filterList[0][column.prop] = row[column.prop];
            }
        },
        async handleEnterEvent(params) {
            let _this = this;
            let {row, column} = params;
            let nextRow = _this.dataList.filter(item => item._index === row._index + 1);
            if (column.property === 'check_qty') {
                if (_this.$utils.isNotEmptyList(nextRow)) {
                    _this.JxcStockInventoryFormTable.setActiveCell(nextRow[0], 'check_qty');
                }
                return;
            }
            if (column.property === 'note_info') {
                if (_this.$utils.isNotEmptyList(nextRow)) {
                    _this.JxcStockInventoryFormTable.setActiveCell(nextRow[0], 'note_info');
                }
                return;
            }
        },
    },
}
</script>

<style lang="less" rel="stylesheet/less" scoped>
.inventory_form_container {
    width: 100%;
    height: 100%;
    overflow: hidden;

    /deep/ .btn_area {
        display: flex;

        .btn_area_left {
            width: 60%;
            text-align: left;
            margin-bottom: 10px;
        }

        .btn_area_right {
            width: 40%;
            text-align: right;
            margin-bottom: 10px;
        }
    }
}
</style>
